package com.zhouyu.proxy;

import com.zhouyu.common.Invocation;
import com.zhouyu.common.URL;
import com.zhouyu.loadbalance.Loadbalance;
import com.zhouyu.protocol.HttpClient;
import com.zhouyu.register.MapRemoteRegister;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.List;

/**
 * 代理工厂
 */
public class ProxyFactory {
    /**
     * 代理
     * @param interfaceClass
     * @return
     * @param <T>
     */
    public static <T> T getProxy(Class interfaceClass) {
        //动态代理=》类加载器，类集合，InvocationHandler
        Object proxyInstance = Proxy.newProxyInstance(interfaceClass.getClassLoader(), new Class[]{interfaceClass}, new InvocationHandler() {
            //
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                //方法四要素：接口名，方法名，参数类型，参数数据
                Invocation invocation = new Invocation(interfaceClass.getName(), method.getName(),
                        method.getParameterTypes(), args);

                HttpClient httpClient = new HttpClient();

                // 服务发现
                List<URL> list = MapRemoteRegister.get(interfaceClass.getName());
                //负载均衡，随机分配
                URL url = Loadbalance.random(list);

                // 服务调用
                String result = httpClient.send(url.getHostname(), url.getPort(), invocation);

                return result;

            }
        });

        return (T) proxyInstance;
    }
}
